<template>
  <div class="hot-projects">
    <div class="header-section">


      <h2 class="section-title">
        <span class="fire-icon">🔥</span> 热门捐赠项目
        <span class="subtitle">探索最受欢迎的公益项目</span>
      </h2>
      
      <!-- 个人中心按钮 -->
      <button class="nav-btn profile-btn" @click="goToProfile">
         <span class="nav-icon">返回</span>
      </button>

      <div class="search-container">
        <div class="search-input-wrapper">
          <span class="search-icon">🔍</span>
          <input 
            v-model="searchQuery" 
            type="text" 
            placeholder="搜索项目名称或描述..." 
            class="search-input"
            @input="handleSearch"
          >
          <button v-if="searchQuery" class="clear-search" @click="clearSearch">×</button>
        </div>
      </div>
    </div>

    <div v-if="loading" class="loading-container">
      <div class="loading-spinner"></div>
      <p>正在加载项目数据...</p>
    </div>

    <div v-else>
      <div v-if="filteredProjects.length === 0 && searchQuery" class="no-results">
        <div class="no-results-icon">🔍</div>
        <p>没有找到匹配"{{ searchQuery }}"的项目</p>
        <button class="refresh-btn" @click="clearSearch">
          清除搜索
        </button>
      </div>

      <div v-else class="grid-wrapper">
        <div 
          v-for="project in filteredProjects" 
          :key="project.id" 
          class="project-card"
          @click="openModal(project)"
        >
          <div class="project-img-container">
            <div class="project-img" :style="{ 'background-image': `url(${project.image})` }"></div>
            <div class="progress-bar">
              <div class="progress" :style="{ width: `${Math.min(100, (project.raised / project.goal) * 100)}%` }"></div>
            </div>
          </div>
          <div class="project-info">
            <h3 class="project-name">{{ project.name }}</h3>
            <p class="project-short-description">{{ project.shortDescription }}</p>
            <div class="project-meta">
              <span class="raised-amount">{{ project.raised }} ETH</span>
              <span class="goal-amount">/ {{ project.goal }} ETH</span>
            </div>
          </div>
        </div>
      </div>
    </div>

    <div v-if="!loading && filteredProjects.length === 0 && !searchQuery" class="empty-state">
      <div class="empty-icon">📭</div>
      <p class="empty-text">暂无捐赠项目，或链上未添加</p>
      <button class="refresh-btn" @click="loadBlockchainData">
        <span class="refresh-icon">🔄</span> 刷新
      </button>
    </div>

    <!-- 项目详情模态框 -->
    <div v-if="selectedProject" class="modal-overlay" @click.self="closeModal">
      <div class="modal-container">
        <button class="close-btn" @click="closeModal">×</button>
        <div class="modal-content">
          <div class="modal-header">
            <div class="modal-img" :style="{ 'background-image': `url(${selectedProject.image})` }"></div>
            <h3 class="modal-title">{{ selectedProject.name }}</h3>
          </div>
          <div class="modal-body">
            <div class="project-stats">
              <div class="stat-item">
                <span class="stat-label">目标金额</span>
                <span class="stat-value">{{ selectedProject.goal }} ETH</span>
              </div>
              <div class="stat-item">
                <span class="stat-label">已筹集</span>
                <span class="stat-value">{{ selectedProject.raised }} ETH</span>
              </div>
              <div class="stat-item">
                <span class="stat-label">完成度</span>
                <span class="stat-value">{{ Math.min(100, Math.round((selectedProject.raised / selectedProject.goal) * 100)) }}%</span>
              </div>
            </div>
            
            <div class="progress-container">
              <div class="progress-bar">
                <div class="progress" :style="{ width: `${Math.min(100, (selectedProject.raised / selectedProject.goal) * 100)}%` }"></div>
              </div>
            </div>
            
            <div class="project-description">
              <h4>项目介绍</h4>
              <p>{{ selectedProject.description }}</p>
            </div>
            
            <button class="donate-btn" @click="donateToProject(selectedProject.id)">
              💰 立即捐赠
            </button>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, computed, onMounted } from 'vue';
import Web3 from 'web3';
import contractData from 'E:/Vue3/vite-project/artifacts/contracts/DonationPlatform.sol/DonationPlatform.json';
import { useRouter } from 'vue-router'

const router = useRouter()
const web3 = ref(null);
const contract = ref(null);
const account = ref('');
const projects = ref([]);
const loading = ref(true);
const selectedProject = ref(null);
const searchQuery = ref('');


// 计算属性，根据搜索条件过滤项目
const filteredProjects = computed(() => {
  if (!searchQuery.value) {
    return projects.value;
  }
  
  const query = searchQuery.value.toLowerCase();
  return projects.value.filter(project => 
    project.name.toLowerCase().includes(query) || 
    project.shortDescription.toLowerCase().includes(query) ||
    project.description.toLowerCase().includes(query)
  );
});

const openModal = (project) => {
  selectedProject.value = project;
};

const closeModal = () => {
  selectedProject.value = null;
};

const donateToProject = (projectId) => {
  alert(`捐赠给项目 ${projectId}`);
  router.push('/MyMessage')
};

const handleSearch = () => {
  // 搜索功能由计算属性处理
};

const clearSearch = () => {
  searchQuery.value = '';
};

const loadBlockchainData = async () => {
  loading.value = true;
  try {
    if (!window.ethereum) {
      throw new Error('请安装MetaMask钱包并刷新页面');
    }

    // 初始化web3
    web3.value = new Web3(window.ethereum);
    
    // 获取账户
    const accounts = await window.ethereum.request({ method: 'eth_requestAccounts' });
    account.value = accounts[0];
    
    // 初始化合约
    contract.value = new web3.value.eth.Contract(
      contractData.abi, 
      '0x1f936366c9b21fC9343BC2DC710031aa01be072E'
    );

    // 加载项目数据 - 使用正确的getProject方法
    const count = await contract.value.methods.projectCount().call();
    const loadedProjects = [];

    for (let i = 1; i <= count; i++) {
      const p = await contract.value.methods.getProject(i).call();
      
      loadedProjects.push({
        id: p.id,
        name: p.name,
        shortDescription: p.shortDescription,
        description: p.description,
        goal: web3.value.utils.fromWei(p.goal, 'ether'),
        raised: web3.value.utils.fromWei(p.raised, 'ether'),
        progress: p.progress,
        donors: p.donors,
        tag: p.tag,
        status: p.status,
        image: p.image || '默认图片URL',
        walletAddress: p.walletAddress
      });
    }

    projects.value = loadedProjects;
  } catch (error) {
    console.error('加载链上数据失败:', error);
    alert(`错误: ${error.message}`);
  } finally {
    loading.value = false;
  }
};

// 返回上一页
const goBack = () => {
  router.go(-1)
};

// 前往个人中心
const goToProfile = () => {
  router.go(-1)
};

onMounted(() => {
  loadBlockchainData();
});
</script>

<style scoped>
.hot-projects {
  padding: 32px 24px;
  background-color: #f8fafc;
  max-width: 1200px;
  margin: 0 auto;
  font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
  min-height: 80vh;
}

.header-section {
  margin-bottom: 32px;
  position: relative;
}

.section-title {
  font-size: 28px;
  font-weight: 700;
  margin-bottom: 16px;
  text-align: center;
  color: #1e293b;
  position: relative;
  display: flex;
  flex-direction: column;
  align-items: center;
}

.fire-icon {
  font-size: 36px;
  margin-bottom: 8px;
  animation: pulse 1.5s infinite;
}

@keyframes pulse {
  0% { transform: scale(1); }
  50% { transform: scale(1.1); }
  100% { transform: scale(1); }
}

.subtitle {
  font-size: 16px;
  font-weight: 400;
  color: #64748b;
  margin-top: 8px;
}

.search-container {
  max-width: 600px;
  margin: 0 auto;
  padding: 0 16px;
}

.search-input-wrapper {
  position: relative;
  display: flex;
  align-items: center;
}

.search-icon {
  position: absolute;
  left: 14px;
  font-size: 18px;
  color: #94a3b8;
}

.search-input {
  width: 100%;
  padding: 12px 16px 12px 42px;
  border: 1px solid #e2e8f0;
  border-radius: 8px;
  font-size: 16px;
  transition: all 0.2s;
  box-shadow: 0 1px 3px rgba(0, 0, 0, 0.05);
}

.search-input:focus {
  outline: none;
  border-color: #3b82f6;
  box-shadow: 0 0 0 3px rgba(59, 130, 246, 0.2);
}

.clear-search {
  position: absolute;
  right: 12px;
  background: none;
  border: none;
  font-size: 20px;
  color: #94a3b8;
  cursor: pointer;
  padding: 0;
  width: 24px;
  height: 24px;
  display: flex;
  align-items: center;
  justify-content: center;
  border-radius: 50%;
}

.clear-search:hover {
  background-color: #f1f5f9;
  color: #64748b;
}

.grid-wrapper {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(280px, 1fr));
  gap: 24px;
}

.project-card {
  background-color: white;
  border-radius: 12px;
  overflow: hidden;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.08);
  cursor: pointer;
  transition: all 0.3s ease;
  display: flex;
  flex-direction: column;
}

.project-card:hover {
  transform: translateY(-5px);
  box-shadow: 0 8px 20px rgba(0, 0, 0, 0.12);
}

.project-img-container {
  position: relative;
  height: 160px;
}

.project-img {
  width: 100%;
  height: 100%;
  background-size: cover;
  background-position: center;
  background-repeat: no-repeat;
}

.progress-bar {
  height: 6px;
  background-color: #e2e8f0;
  position: absolute;
  bottom: 0;
  left: 0;
  right: 0;
}

.progress {
  height: 100%;
  background: linear-gradient(90deg, #3b82f6, #6366f1);
  transition: width 0.5s ease;
  border-radius: 0 3px 3px 0;
}

.project-info {
  padding: 16px;
  flex-grow: 1;
  display: flex;
  flex-direction: column;
}

.project-name {
  font-size: 18px;
  font-weight: 600;
  margin-bottom: 8px;
  color: #1e293b;
  display: -webkit-box;
  -webkit-line-clamp: 2;
  -webkit-box-orient: vertical;
  overflow: hidden;
}

.project-short-description {
  font-size: 14px;
  color: #64748b;
  margin-bottom: 12px;
  line-height: 1.5;
  display: -webkit-box;
  -webkit-line-clamp: 2;
  -webkit-box-orient: vertical;
  overflow: hidden;
}

.project-meta {
  margin-top: auto;
  font-size: 15px;
}

.raised-amount {
  font-weight: 600;
  color: #3b82f6;
}

.goal-amount {
  color: #64748b;
}

.loading-container {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  padding: 40px 0;
}

.loading-spinner {
  width: 50px;
  height: 50px;
  border: 4px solid #e2e8f0;
  border-top-color: #3b82f6;
  border-radius: 50%;
  animation: spin 1s linear infinite;
  margin-bottom: 16px;
}

@keyframes spin {
  to { transform: rotate(360deg); }
}

.empty-state {
  text-align: center;
  padding: 40px 0;
}

.empty-icon {
  font-size: 60px;
  margin-bottom: 16px;
  opacity: 0.7;
  animation: bounce 2s infinite;
}

@keyframes bounce {
  0%, 20%, 50%, 80%, 100% { transform: translateY(0); }
  40% { transform: translateY(-20px); }
  60% { transform: translateY(-10px); }
}

.empty-text {
  font-size: 16px;
  color: #64748b;
  margin-bottom: 20px;
}

.no-results {
  text-align: center;
  padding: 60px 0;
}

.no-results-icon {
  font-size: 48px;
  margin-bottom: 16px;
  opacity: 0.6;
}

.refresh-btn {
  background-color: #3b82f6;
  color: white;
  border: none;
  padding: 12px 24px;
  border-radius: 8px;
  font-size: 14px;
  cursor: pointer;
  transition: all 0.2s;
  display: inline-flex;
  align-items: center;
  box-shadow: 0 2px 5px rgba(59, 130, 246, 0.3);
}

.refresh-btn:hover {
  background-color: #2563eb;
  transform: translateY(-2px);
  box-shadow: 0 4px 8px rgba(59, 130, 246, 0.4);
}

.refresh-icon {
  margin-right: 8px;
  font-size: 16px;
}

/* 模态框样式 */
.modal-overlay {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background-color: rgba(0, 0, 0, 0.5);
  display: flex;
  justify-content: center;
  align-items: center;
  z-index: 1000;
  backdrop-filter: blur(5px);
}

.modal-container {
  background-color: white;
  border-radius: 16px;
  width: 90%;
  max-width: 600px;
  max-height: 90vh;
  overflow-y: auto;
  position: relative;
  box-shadow: 0 10px 30px rgba(0, 0, 0, 0.2);
  animation: modalFadeIn 0.3s ease-out;
}

@keyframes modalFadeIn {
  from {
    opacity: 0;
    transform: translateY(20px);
  }
  to {
    opacity: 1;
    transform: translateY(0);
  }
}

.close-btn {
  position: absolute;
  top: 16px;
  right: 16px;
  background: none;
  border: none;
  font-size: 24px;
  font-weight: bold;
  color: #64748b;
  cursor: pointer;
  width: 36px;
  height: 36px;
  display: flex;
  align-items: center;
  justify-content: center;
  border-radius: 50%;
  transition: all 0.2s;
  z-index: 10;
}

.close-btn:hover {
  background-color: #f1f5f9;
  color: #1e293b;
}

.modal-content {
  padding: 40px;
}

.modal-header {
  margin-bottom: 24px;
  text-align: center;
}

.modal-img {
  height: 200px;
  width: 100%;
  border-radius: 12px;
  background-size: cover;
  background-position: center;
  margin-bottom: 20px;
}

.modal-title {
  font-size: 24px;
  font-weight: 700;
  color: #1e293b;
  margin-bottom: 8px;
}

.project-stats {
  display: grid;
  grid-template-columns: repeat(3, 1fr);
  gap: 16px;
  margin-bottom: 24px;
}

.stat-item {
  background-color: #f8fafc;
  padding: 16px;
  border-radius: 12px;
  text-align: center;
}

.stat-label {
  display: block;
  font-size: 14px;
  color: #64748b;
  margin-bottom: 8px;
}

.stat-value {
  font-size: 18px;
  font-weight: 600;
  color: #1e293b;
}

.progress-container {
  margin: 24px 0;
}

.project-description {
  margin: 24px 0;
}

.project-description h4 {
  font-size: 18px;
  color: #1e293b;
  margin-bottom: 12px;
}

.project-description p {
  font-size: 15px;
  color: #475569;
  line-height: 1.8;
}

.donate-btn {
  width: 100%;
  background: linear-gradient(90deg, #3b82f6, #6366f1);
  color: white;
  border: none;
  padding: 16px;
  border-radius: 12px;
  font-size: 16px;
  font-weight: 600;
  cursor: pointer;
  transition: all 0.2s;
  margin-top: 24px;
  box-shadow: 0 4px 12px rgba(59, 130, 246, 0.3);
}

.donate-btn:hover {
  transform: translateY(-2px);
  box-shadow: 0 6px 16px rgba(59, 130, 246, 0.4);
}

/* 导航按钮 */
.nav-btn {
  position: absolute;
  top: 24px;
  padding: 8px 16px;
  border: none;
  border-radius: 8px;
  font-size: 14px;
  font-weight: 500;
  cursor: pointer;
  transition: all 0.2s;
  display: flex;
  align-items: center;
  gap: 8px;
}

.back-btn {
  left: 24px;
  background-color: #f3f4f6;
  color: #1e293b;
}

.back-btn:hover {
  background-color: #e5e7eb;
}

.profile-btn {
  right: 24px;
  background-color: #3b82f6;
  color: white;
}

.profile-btn:hover {
  background-color: #2563eb;
}

.nav-icon {
  font-size: 16px;
}

@media (max-width: 768px) {
  .grid-wrapper {
    grid-template-columns: 1fr;
  }
  
  .hot-projects {
    padding: 24px 16px;
  }
  
  .section-title {
    font-size: 24px;
  }
  
  .project-stats {
    grid-template-columns: 1fr;
  }
  
  .modal-content {
    padding: 24px;
  }
  
  .modal-img {
    height: 160px;
  }
  
  .back-btn {
    left: 16px;
    top: 16px;
  }
  
  .profile-btn {
    right: 16px;
    top: 16px;
  }
  
  .search-container {
    padding: 0;
  }
}
</style>